import * as roleMenuService from './sys_role_menu';
import {SysRoleDao} from "@common/dao/sys_role.dao";

export async function getRoles(query: any, offset: string|number = 0, limit: string|number = 10) {
    // query 参数暂未用到，如需支持可扩展
    return await SysRoleDao.getRoles(offset, limit);
}

export async function getRoleOptions(query: any) {
    return await SysRoleDao.getRoleOptions();
}

export async function getRoleById(role_id: number) {
    const role = await SysRoleDao.getRoleById(role_id);
    if (role) {
        const menus = await roleMenuService.getRoleMenus(role_id);
        return {
            ...role,
            menu_ids: menus.map((item: any) => item.menu_id)
        };
    }
    return role;
}

export async function createRole(data: any) {
    const { menu_ids, ...roleData } = data;
    const role_id = await SysRoleDao.createRole(roleData);
    
    if (menu_ids && Array.isArray(menu_ids) && menu_ids.length > 0) {
        await roleMenuService.createRoleMenus(role_id, menu_ids);
    }
    
    return role_id;
}

export async function updateRole(role_id: number, data: any) {
    // 保护ID为1的超级管理员角色
    if (role_id === 1) {
        throw new Error('超级管理员角色不可修改');
    }
    
    const { menu_ids, ...roleData } = data;
    const result = await SysRoleDao.updateRole(role_id, roleData);
    
    if (menu_ids !== undefined) {
        await roleMenuService.updateRoleMenus(role_id, menu_ids || []);
    }
    
    return result;
}

export async function deleteRole(role_id: number) {
    // 保护ID为1的超级管理员角色
    if (role_id === 1) {
        throw new Error('超级管理员角色不可删除');
    }
    
    // 删除角色时同时删除菜单关联
    await roleMenuService.deleteRoleMenus(role_id);
    return await SysRoleDao.deleteRole(role_id);
} 